<template>
  <div class="page_padding">
    <MyNavBar class="nav" @goback="goback" :title="Pagetitle"></MyNavBar>
    <StatisticTab :statisticInfo="statisticInfo">
      <div class="tips" slot="tips">温馨提示：本季度可评“好”等次{{ goodNum }}人, 已评{{ chooseGoodNum }}人</div>
    </StatisticTab>
    <div class="cont-box">
      <div class="score_tip">
        <div class="word">
          <span class="title-text">考核结果等次：</span>
        </div>
        <div class="standard" @click="onStandardShow">评分标准</div>
      </div>
      <div class="score_type">
        <div class="finish">
          <div class="score_list" v-for="item in userList" :key="item.leaderId">
            <div class="table-title common">分管负责人：{{ item.leaderName }}</div>
            <div class="score_li" v-for="li in item.userAssessDataResponseVOS" :key="li.userId">
              <score-option-only-group
                :userInfo="li"
                :sortIndex="li.shortIndex"
                :goodNum="goodNum"
                :rollListAll="userList"
                :quarterNow="quarterNow"
                :calcRule="calcRule"
                :needPlusMinusPoints="needPlusMinusPoints"
                :needPeopleAssess="needPeopleAssess"
                :showHistory="showHistory"></score-option-only-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="fead_boot">
      <div @click="saveMark()" class="inform btn_li">保存</div>
      <div class="btn_li" @click="postMarkSub()" v-if="statisticInfo.numNoSub === 0">提交</div>
      <div class="btn_li" @click="urgeSub()" :class="{ no_nform: statisticInfo.isUrgeAll === '0' }" v-else>
        {{ statisticInfo.isUrgeAll === '0' ? '已催报' : '全部催报' }}
      </div>
    </div>

    <van-dialog
      v-model="subbmitShow"
      title="提醒"
      show-cancel-button
      @confirm="onSubbmit"
      @cancle="subbmitShow = 'false'">
      <div class="message">{{ tipMessage }}</div>
      <OtherTable :otherList="otherLists"></OtherTable>
    </van-dialog>

    <ScoringCriteria :criteriaShow="criteriaShow" @close="closeCriteria" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import MyNavBar from '@com/MyNavBar'
import ScoreOptionOnlyGroup from './components/ScoreOptionOnlyGroup'
import OtherTable from './components/OtherTable'
import ScoringCriteria from './components/ScoringCriteria.vue'
import { submitAllAssess, getUserAssessData, saveSimpleAssess, getCheckSubmitAllAssess } from '@api/api-comment.js'
import { saveUrgeByNeedDeal } from '@api/api-documentary.js'
import StatisticTab from './components/StatisticTab.vue'
export default {
  name: 'ScoreNewsOnlyGroup',
  components: {
    MyNavBar,
    ScoreOptionOnlyGroup,
    OtherTable,
    ScoringCriteria,
    StatisticTab,
  },
  props: {},
  data() {
    return {
      recordType: '', //01-02 月度 01-03 季度
      Pagetitle: '季度评价',
      scoringId: '',
      busSign: '', // 打分类型
      statisticInfo: {
        numAll: 0, // 总人数
        numNo: 0, // 未评
        numHas: 0, // 已评
        numNoSub: 0, // 未提交
        isUrgeAll: '', // 是否催报
      },
      requestType: '', //请求用户类型 1表示已评议
      subbmitShow: false,
      criteriaShow: false,
      userList: [],
      tipMessage: '',
      sortWay: true,
      subbmitSatus: 0,
      otherList: [],
      otherLists: [],
      lenderUserList: [],
      commonUserList: [],
      noSubmitData: [],
      goodNum: 0,
      chooseGoodNum: 0,
      quarterNow: 0,
      calcRule: [],
      needPlusMinusPoints: true, // 是否显示加分项
      needPeopleAssess: true, // 是否显示民主测评
      showHistory: false, // 是否显示历史评价
    }
  },
  computed: {
    ...mapGetters(['activeEvaluation']),
  },
  created() {},
  mounted() {
    this.Pagetitle = this.$route.query.needDealName || '季度评价'
    this.recordType = this.$route.query.recordType
    this.scoringId = this.$route.query.saScoringId
    this.busSign = this.$route.query.busSign
    this.processInstanceId = this.$route.query.processInstanceId
    this.taskId = this.$route.query.taskId
    this.requestType = this.$route.query.requestType || 0
    this.noteId = this.$route.query.noteId
    this.getPageGradeDataList('0')
  },
  watch: {
    userList: {
      handler(news) {
        let rollList = []
        news.forEach(item => {
          item.userAssessDataResponseVOS.forEach(li => {
            rollList.push(li)
          })
        })
        const arr = rollList.filter(item => {
          return item.assessRank === '1'
        })
        this.chooseGoodNum = arr.length
        this.setTopNum(rollList)
      },
      deep: true,
      immediate: true,
    },
    otherList: {
      handler(news) {
        this.otherLists = news
      },
      deep: true,
    },
    Pagetitle: {
      handler(news) {
        if (news.indexOf('第一季度') !== -1) {
          this.quarterNow = 0
        } else if (news.indexOf('第二季度') !== -1) {
          this.quarterNow = 1
        } else if (news.indexOf('第三季度') !== -1) {
          this.quarterNow = 2
        } else if (news.indexOf('第四季度') !== -1) {
          this.quarterNow = 3
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 判断数据是否已经填写完
    postMark() {
      if (this.statisticInfo.numAll !== this.statisticInfo.numHas) {
        this.tipMessage = `还有${this.statisticInfo.numAll - this.statisticInfo.numHas}人未评价，请完成评价后再提交结果`
      } else {
        getCheckSubmitAllAssess({
          isCheckGood: 1,
          needId: this.$route.query.needId,
        }).then(res => {
          if (res.status === 200) {
            this.subbmitSatus = res.data.status
            if (res.data.status == 0) {
              this.tipMessage = '您确定要提交所有评分吗？'
            } else {
              this.tipMessage = res.data.tips
            }
          }
        })
      }
      this.subbmitShow = true
    },
    goback() {
      this.$store.state.alive = false
      this.$router.go(-1)
    },
    getPageGradeDataList(type) {
      this.getUserAssessData(type)
    },
    onSubbmit() {
      if (this.subbmitSatus == 2 || this.statisticInfo.numAll !== this.statisticInfo.numHas) {
        this.subbmitShow = false
      } else {
        submitAllAssess({ needId: this.$route.query.needId, isCheckGood: 0 }).then(res => {
          if (res.status === 200) {
            this.$toast.success('提交结果成功')
            setTimeout(() => {
              this.$store.state.stateAlive = false
              this.$router.go(-2)
            }, 500)
          }
        })
      }
    },
    onStandardShow() {
      this.criteriaShow = true
    },
    closeCriteria() {
      this.criteriaShow = false
    },
    getUserAssessData(type) {
      getUserAssessData({
        needId: this.$route.query.needId,
      }).then(res => {
        this.calcRule = res.data.calcRule
        this.needPlusMinusPoints = res.data.needPlusMinusPoints
        this.needPeopleAssess = res.data.needPeopleAssess
        this.showHistory = res.data.showHistory
        this.statisticInfo.isUrgeAll = res.data.isUrge
        this.goodNum = res.data.goodRankCount
        let num = 0
        let rollList = []
        let userListArr = res.data.leaderGroupUserAssessVOS || []
        userListArr.forEach(item => {
          item.userAssessDataResponseVOS.sort((a, b) => {
            return Number(a.leaderAssessRank) - Number(b.leaderAssessRank)
          })
          item.userAssessDataResponseVOS.forEach(li => {
            li.extraData = {
              id: '',
              title: '',
              entryCont: '',
              audioList: [],
            }
            li.reviewsaData = {
              id: '',
              title: '',
              entryCont: '',
              audioList: [],
            }
            li.scoringRadio = ''
            if (res.data.isSetLeaderAssess === 1) {
              if (!li.mainLeaderAssessRank && li.leaderAssessRank) {
                li.mainLeaderAssessRank = li.leaderAssessRank
                li.mainLeaderAssessScore = li.leaderAssessScore
              }
            }
            num++
            li.shortIndex = num
            rollList.push(li)
          })
          this.otherList = rollList
          this.userList = userListArr
        })
      })
    },
    saveMark(type) {
      let rollList = []
      this.userList.forEach(item => {
        item.userAssessDataResponseVOS.forEach(li => {
          rollList.push(li)
        })
      })
      let arrSave = []
      for (let i = 0; i < rollList.length; i++) {
        let item = rollList[i]
        if (item.assessRank) {
          if (item.assessRank == 3 && !item.reviewsaData.entryCont.trim() && item.leaderAssessRank !== '3') {
            this.$toast.fail(`${item.userName}等次评价为“一般”，需要填写领导点评`)
            return
          }
          if (item.assessRank == 4 && !item.remark.trim() && item.leaderAssessRank !== '4') {
            this.$toast.fail(`${item.userName}等次评价为“较差”，需要填写备注原因`)
            return
          }
          item.status = '2'
          arrSave.push({
            assessRank: item.assessRank,
            saveStatus: '1',
            scoringId: item.saScoringId,
            processInstanceId: item.processInstanceId,
            taskId: item.taskId,
            totalScore: item.totalScore,
            scoringSuggestVO: {
              suggestion: item.reviewsaData.entryCont,
              voiceList: item.reviewsaData.audioList,
            },
            scoringExpressionVO: {
              expression: item.extraData.entryCont,
              voiceList: item.extraData.audioList,
            },
            remark: item.remark,
          })
        }
      }
      saveSimpleAssess(arrSave).then(res => {
        if (res.status == 200) {
          if (res.data.status === 0) {
            this.otherList = rollList
            if (type === 'sub') {
              this.postMark()
            } else {
              this.$toast.success('保存成功')
            }
          } else {
            this.$toast.fail(res.data.tips)
          }
        }
      })
    },
    // 催报
    urgeSub() {
      if (this.statisticInfo.isUrgeAll === '0') {
        return
      }
      let message = '',
        arr = []
      let arrUN = this.otherList.filter(item => {
        return item.status == 0
      })
      arrUN.forEach(item => {
        arr.push(item.userName)
      })
      message = `本季度个人工作汇总未完成人员 ${arr.join('、')}，您确定要进行催报吗？`
      this.$dialog
        .confirm({
          title: '提示',
          message: message,
        })
        .then(() => {
          saveUrgeByNeedDeal({
            needId: this.$route.query.needId,
            type: 2,
            urgeUserId: '',
            optionUserId: localStorage.userId,
            tenantId: localStorage.tenantId,
          })
            .then(res => {
              if (res.status === 200) {
                this.statisticInfo.isUrgeAll = '0'
              }
            })
            .catch(err => {})
        })
        .catch(() => {
          // on cancel
        })
    },
    setTopNum(list) {
      let [total, noScoreNum, scoredNum, noSubmitNum] = [0, 0, 0, 0]
      list.forEach(item => {
        total++
        if (item.status == 1) {
          noScoreNum++
        } else if (item.status == 2 || item.status == 3) {
          scoredNum++
        } else if (item.status == 0) {
          noSubmitNum++
        }
      })

      this.statisticInfo.numAll = total
      this.statisticInfo.numNo = noScoreNum
      this.statisticInfo.numHas = scoredNum
      this.statisticInfo.numNoSub = noSubmitNum
    },
    postMarkSub() {
      this.saveMark('sub')
    },
  },
}
</script>

<style lang="scss" scoped>
.page_padding {
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  /deep/ .van-overlay {
    position: fixed;
  }
  .cont-box {
    margin: 5px 16px;
    border-radius: 5px;
    position: relative;
    background: #fff;
    flex: 1;
    display: flex;
    flex-direction: column;
    padding-bottom: 60px;
    overflow: hidden;
    .tip {
      color: rgb(173, 115, 22);
      width: 100%;
      padding: 12px;
      background: #fff8ed;
      font-size: 13px;
      font-weight: bold;
      text-align: center;
    }
    .score_tip {
      width: 100%;
      padding: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .standard {
        color: #666666;
        font-weight: normal;
      }
    }
    .score_type {
      font-size: 14px;
      padding: 0 14px;
      padding-bottom: 15px;
      overflow-y: auto;
      flex: 1;
      .table-title {
        border-bottom: 1px solid #dfdfdf;
        padding-bottom: 10px;
      }
      .common {
        margin-top: 12px;
      }
      .finish {
        padding-bottom: 15px;
      }
    }
  }
  .fead_boot {
    .inform {
      background: #f5f5f5;
      color: #999999;
    }
    .no_nform {
      opacity: 0.5;
    }
  }
  /deep/.van-dialog__content {
    padding: 8px 0;
  }
  .message {
    padding: 0 15px;
    // font-size: 14px;
    margin-bottom: 10px;
  }
}
</style>
